package com.littcore.saap.system.web;

import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.littcore.common.Utility;
import com.littcore.dao.page.IPageList;
import com.littcore.dao.ql.PageParam;
import com.littcore.exception.NotLoginException;
import com.littcore.module.annotation.Func;
import com.littcore.saap.common.vo.LoginUserVo;
import com.littcore.saap.core.common.SaapConstants;
import com.littcore.saap.core.common.SaapConstants.IsolatedMode;
import com.littcore.saap.core.common.SaapConstants.TenantOrderType;
import com.littcore.saap.core.common.SaapConstants.TenantProductType;
import com.littcore.saap.core.module.tenant.config.TenantDefConfig;
import com.littcore.saap.core.module.tenant.config.TenantTypeConfigManager;
import com.littcore.saap.core.web.util.LoginUtils;
import com.littcore.saap.system.biz.ITenantBizService;
import com.littcore.saap.system.dao.TenantDao;
import com.littcore.saap.system.po.Tenant;
import com.littcore.saap.system.po.TenantOrder;
import com.littcore.saap.system.service.ITenantMemberService;
import com.littcore.saap.system.service.ITenantOrderService;
import com.littcore.saap.system.vo.TenantOrderVo;
import com.littcore.util.BeanCopier;
import com.littcore.web.mvc.action.BaseController;
import com.littcore.web.util.WebUtils;

/**
 * 
 * Order controller.
 * <pre><b>Description：</b>
 *    Order Management
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">Bob.cai</a>
 * @since 2014-05-14
 * @version 1.0
 */
@Controller
public class TenantOrderController extends BaseController
{
	private final static Logger logger = LoggerFactory.getLogger(TenantOrderController.class);

	@Resource
	private ITenantOrderService tenantOrderService;
	
	@Resource
  private ITenantBizService tenantBizService;
	
	 @Resource
	  private ITenantMemberService tenantMemberService;
	 
	 @Resource
	 private TenantDao tenantDao;
	 
	  @Resource
	  private MessageSource messageSource;
	
	/**
	 * default page.
	 * 
	 */
	@Func(funcCode="query", moduleCode="tenant.tenantOrder", enableLog=false, enablePermission=false) 
	@RequestMapping 
	public ModelAndView index(WebRequest request, ModelMap modelMap) throws NotLoginException
	{	
		LoginUserVo loginUserVo = (LoginUserVo)super.getLoginVo();
		
		//get params from request
		String code = request.getParameter("code");
		String name = request.getParameter("name");
				
		//package the params
		PageParam pageParam = WebUtils.getPageParam(request);
		pageParam.addCond("tenantId", loginUserVo.getTenantId());
		pageParam.addCond("code", code);	
		pageParam.addCond("name", name);	
		pageParam.addCond("createBy",LoginUtils.getLoginOpId());
		pageParam.addCond("isDeleted", false);	
		//Get page result
		IPageList pageList = tenantOrderService.listPage(pageParam);		
		
		//return params to response
		modelMap.addAttribute("pageParam", pageParam);	
		modelMap.addAttribute("pageList", pageList);	
		
    return new ModelAndView("/system/tenantOrder/index");	
	
	} 	
	
	
	 @Func(funcCode="query", moduleCode="tenant.tenantOrder", enableLog=false, enablePermission=false)  
	  @RequestMapping
	  public ModelAndView getTenantOrderByTenant(WebRequest request, ModelMap modelMap) 
	  {    
	     int tenantId=LoginUtils.getTenantId();
	     Locale locale=LoginUtils.getLocale();
	     PageParam pageParam = WebUtils.getPageParam(request);
	     pageParam.addCond("tenantId", tenantId); ;  
	     //Get page result
	     IPageList pageList = tenantOrderService.listPage(pageParam);
	     List<Map<String,Object>> rsList= pageList.getRsList();
	     if(rsList!=null){
	        for(Map<String,Object> rs:rsList){
	           TenantOrder order=(TenantOrder)(rs.get("TenantOrder"));
	           TenantOrderVo orderVo=BeanCopier.copy(order, TenantOrderVo.class);
	           String orderTypeName=messageSource.getMessage("dictparam."+"tenantOrder-type"+"."+orderVo.getOrderType(), null, locale);
	           orderVo.setOrderTypeName(orderTypeName);
	           String orderStatusName=messageSource.getMessage("dictparam."+"tenantOrder-status"+"."+orderVo.getStatus(), null, locale);

	           orderVo.setOrderStatusName(orderStatusName);
	           rs.put("TenantOrder",orderVo);
	        }
	         
	        
	     }
	     
	     modelMap.addAttribute("data",rsList);
	     
	    return null;
	  }
	 
	 
	
	/**
	 * Add Page.
	 * 
	 * @return ModelAndView
	 */	
	@Func(funcCode="add", moduleCode="tenant.tenantOrder", enableLog=false, enablePermission=false)  
	@RequestMapping
	public ModelAndView add() 
	{        
  	return new ModelAndView("/system/tenantOrder/add");
  }
	
	/**
	 * Edit Page.
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="edit", moduleCode="tenant.tenantOrder", enableLog=false, enablePermission=false)  
	@RequestMapping 
	public ModelAndView edit(@RequestParam Integer id) 
	{ 
		TenantOrder tenantOrder = tenantOrderService.load(id);		
        return new ModelAndView("/system/tenantOrder/edit").addObject("tenantOrder", tenantOrder);
    }	
    
	/**
	 * Show Page.
	 * 
	 * @param id 
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="query", moduleCode="tenant.tenantOrder", enableLog=false, enablePermission=false)  
	@RequestMapping 
	public ModelAndView show(@RequestParam Integer id) 
	{ 
		TenantOrder tenantOrder = tenantOrderService.load(id);		
        return new ModelAndView("/system/tenantOrder/show").addObject("tenantOrder", tenantOrder);
    }   
    
    /**
	 * Save.
	 * @throws Exception
	 */
	@Func(funcCode="add",moduleCode="tenant.tenantOrder", enablePermission=false)
	@RequestMapping 
	public ModelAndView save(@RequestParam String tenantCode, @RequestParam String tenantAlias, @RequestParam String bagCode
			, @RequestParam int price, @RequestParam int quantity,@RequestParam String payChannel) throws Exception
	{	
		int isolatedMode = IsolatedMode.NO_ISOLATION;	//TODO 目前均不隔离，需要具体实现
		int createBy = LoginUtils.getLoginOpId().intValue();
		
		Integer tenantOrderId = tenantOrderService.save(SaapConstants.TenantOrderType.NEW, tenantCode, tenantAlias, bagCode, isolatedMode, price, quantity, createBy, null);
		TenantOrder tenantOrder = tenantOrderService.load(tenantOrderId);
		return new ModelAndView("jsonView").addObject("tenantOrder", tenantOrder);
	}
	
	/**
	 * Update.
	 * @throws Exception
	 */
	@Func(funcCode="edit",moduleCode="tenant.tenantOrder", enablePermission=false)
	@RequestMapping 
	public void update(WebRequest request, ModelMap modelMap) throws Exception
	{
		TenantOrder tenantOrder = tenantOrderService.load(Utility.parseInt(request.getParameter("id")));
		BeanUtils.populate(tenantOrder, request.getParameterMap());
		tenantOrderService.update(tenantOrder);
	}
	
	/**
	 * Delete.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode="delete",moduleCode="tenant.tenantOrder", enablePermission=false)
	@RequestMapping 
	public void delete(@RequestParam Integer id) throws Exception
	{
		tenantOrderService.delete(id);
	}

	/**
	 * Delete Batch.
	 * @throws Exception
	 */
	@Func(funcCode="delete",moduleCode="tenant.tenantOrder", enablePermission=false)
	@RequestMapping 
	public void deleteBatch(@RequestParam(value="ids[]") Integer[] ids) throws Exception
	{
		tenantOrderService.deleteBatch(ids);
	}
	
	 @RequestMapping()
	  public ModelAndView spaceChoose(ModelMap model) throws Exception
	  { 
	     
	     TenantDefConfig[] tenantDefList = TenantTypeConfigManager.getInstance().getConfig().getTenantDefList();    
	   
	    return new ModelAndView("/system/tenantOrder/spaceChoose").addObject("tenantDefList", tenantDefList);   
	  }
	 
	 @RequestMapping()
	  public ModelAndView spaceOrder(@RequestParam String tenantTypeCode, ModelMap model) throws Exception
	  { 
	     TenantDefConfig tenantDef = TenantTypeConfigManager.getInstance().getTenantDefConfig(tenantTypeCode);
	      Tenant tenant=tenantDao.load(LoginUtils.getTenantId());
	    
	    return new ModelAndView("/system/tenantOrder/spaceOrder").addObject("tenantDef", tenantDef).addObject("tenant",tenant);
	  }
	 

   @RequestMapping
   public ModelAndView pay(@RequestParam(required=true) Integer id){
       TenantOrder order=tenantOrderService.load(id);
       return new ModelAndView("/system/tenantOrder/pay").addObject("order",order);
 
   }
	
	 @RequestMapping
	 public ModelAndView payOrder(@RequestParam String tenantTypeCode
	         , @RequestParam String tenantCode, @RequestParam String tenantAlias, @RequestParam String payChannel
	         , @RequestParam Integer quantity, HttpServletRequest request) throws Exception
	     {          

	     TenantDefConfig tenantDef = TenantTypeConfigManager.getInstance().getTenantDefConfig(tenantTypeCode);
	     TenantOrder tenantOrder = new TenantOrder();
	     //生成规则：年月日时分秒+用户ID
	    
	     tenantOrder.setOrderType(TenantOrderType.NEW);
	     tenantOrder.setProductNo(tenantTypeCode);
	     tenantOrder.setProductType(TenantProductType.FUNC);
	     tenantOrder.setTenantId(LoginUtils.getTenantId());
	     tenantOrder.setTenantCode(tenantCode);
	     tenantOrder.setTenantAlias(tenantAlias);    
	     tenantOrder.setIsolatedMode(IsolatedMode.NO_ISOLATION);
	     tenantOrder.setQuantity(quantity);
	     tenantOrder.setPrice(tenantDef.getPrice());
	     tenantOrder.setPayChannel(payChannel);
	     
	     int orderId=tenantOrderService.save(tenantOrder);
	     tenantOrder=tenantOrderService.load(orderId);

       return null;
	     }  
	 


	    
}
